<?php
/**
 * 脚本模块执行时间抽样统计
 * @author wanggang
 *
 */
class OpExecutionTimeSamplingStatistics
{
    private static $_instances = array();
    
    private $_status = FALSE;
    
    private $_startTimes = array();
    
    private $_subEnds = array();
    
    /**
     * 
     * @param int $_ratio 抽样比率
     */
    public function __construct($ratio = 100)
    {
        $this->_status = rand(1, $ratio) === 1;
    }
    
    public function start($id)
    {
        if ($this->_status) {
            $this->_startTimes[$id] = $this->_time();
        }
    }
    
    public function subEnd($id)
    {
        if ($this->_status) {
            $startTime = $this->_startTimes[$id];
            $endTime = $this->_time();
            $executionTime = $endTime - $startTime;
            $this->_subEnds[$id][] = $executionTime;
            $this->_startTimes[$id] = NULL;
        }
    }
    
    public function end($id)
    {
        if ($this->_status) {
            $executionTime = 0;
            if (isset($this->_subEnds[$id])) {
                $executionTime = array_sum($this->_subEnds[$id]);
            }
            
            $startTime = $this->_startTimes[$id];
            if ($startTime !== NULL) {
                $endTime = $this->_time();
                $executionTime += $endTime - $startTime;
            }
            //oa_log_debug('exec time stat:'.$id.':'.$executionTime);
            StatExecutionTime($id, $executionTime);
        }   
    }
    
    private function _time()
    {
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }
    
    public static function getInstance($ratio = 100)
    {
        if (!isset(self::$_instances[$ratio])) {
            self::$_instances[$ratio] = new self($ratio);
        }
        
        return self::$_instances[$ratio];
    }
}

function etss_start($id)
{
    $ratio = 100;
    if (defined('ET_RATIO')) {
        $ratio = ET_RATIO;
    }
    $obj = OpExecutionTimeSamplingStatistics::getInstance($ratio);
    $obj->start($id);
}

function etss_subend($id)
{
    $ratio = 100;
    if (defined('ET_RATIO')) {
        $ratio = ET_RATIO;
    }
    $obj = OpExecutionTimeSamplingStatistics::getInstance($ratio);
    $obj->subEnd($id);
}

function etss_end($id)
{
    $ratio = 100;
    if (defined('ET_RATIO')) {
        $ratio = ET_RATIO;
    }
    $obj = OpExecutionTimeSamplingStatistics::getInstance($ratio);
    $obj->end($id);
}